/*
 * stdafx.c
 *
 *  Created on: Jul 28, 2013
 *      Author: lxzhu
 */
#include "stdafx.h"
int types[][3]={{3,1,2},{5,1,6},{4,6,2},{3,5,4},{4,7,4},{5,5,7},{7,6,6},{7,7,7}};
GLboolean flags[][8]={
		{GL_TRUE,GL_TRUE,GL_FALSE,GL_TRUE,GL_FALSE,GL_TRUE,GL_FALSE,GL_FALSE},
		{GL_TRUE,GL_TRUE,GL_TRUE,GL_FALSE,GL_FALSE,GL_FALSE,GL_TRUE,GL_FALSE},
		{GL_TRUE,GL_FALSE,GL_TRUE,GL_TRUE,GL_TRUE,GL_FALSE,GL_FALSE,GL_FALSE}
};
GLfloat* defaultTransformCallback(GLfloat *a){
	GLfloat *ret=(GLfloat*)malloc(2*sizeof(GLfloat));
	ret[0]=a[0];
	ret[1]=a[1];
	return ret;
}

void divideTriangle(GLfloat* a,
		GLfloat* b,
		GLfloat* c,
		int level,
		int type,
		transform transformCallback){
	if(level<=0){
		drawTriangle(a,b,c,type,transformCallback);
	}else{


		GLfloat v[3][2];
		int idx=0;

		for(idx=0;idx<2;idx++){
			v[0][idx]=(a[idx]+b[idx])/2;
			v[1][idx]=(b[idx]+c[idx])/2;
			v[2][idx]=(a[idx]+c[idx])/2;
		}
        divideTriangle(a,v[0],v[2],level-1,types[type][0],transformCallback);
        divideTriangle(v[0],b,v[1],level-1,types[type][1],transformCallback);
        divideTriangle(v[2],v[1],c,level-1,types[type][2],transformCallback);
        divideTriangle(v[0],v[1],v[2],level-1,7,transformCallback);

	}
}

void drawTriangle(GLfloat *a, GLfloat *b, GLfloat *c,int type,transform transformCallback){
	if(transformCallback==NULL)
		transformCallback=defaultTransformCallback;
	GLfloat *na,*nb,*nc;
	na=transformCallback(a);
	nb=transformCallback(b);
	nc=transformCallback(c);

	glBegin(GL_POLYGON);

    glEdgeFlag(flags[0][type]);
    glVertex2fv(na);

    glEdgeFlag(flags[1][type]);
    glVertex2fv(nb);

    glEdgeFlag(flags[2][type]);
    glVertex2fv(nc);

    glEnd();


    free(na);
    free(nb);
    free(nc);

}

